/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.it;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public final class XmlUtils {
  public static void checkName(Element e, String expectedName) {
    ItCheck.input(e.getTagName().equalsIgnoreCase(expectedName));
  }

  public static String find(Element e, String attributeName) {
    ItCheck.input(e.hasAttribute(attributeName));
    return e.getAttribute(attributeName);
  }

  public static boolean findBoolean(Element e, String attributeName) {
    return xmlValueToBoolean(find(e, attributeName));
  }

  private static boolean xmlValueToBoolean(String s) {
    switch (s) {
      case It.VAL_TRUE: return true;
      case It.VAL_FALSE: return false;
      default: throw new ItInputException();
    }
  }

  public static int findInteger(Element e, String attributeName) {
    return xmlValueToInteger(find(e, attributeName));
  }

  public static int xmlValueToInteger(String s) {
    try {
      return Integer.parseInt(s);
    } catch (NumberFormatException e) {
      throw new ItInputException(e);
    }
  }

  private static Element toElementIfNameMatches(Node node, String name) {
    if (node instanceof Element) {
      Element element = (Element) node;
      if ((name == null) || element.getTagName().equalsIgnoreCase(name)) {
        return element;
      }
    }
    return null;
  }

  public static Element getChild(Element parent, String name) {
    for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
      Element res = toElementIfNameMatches(n, name);
      if (res != null) {
        return res;
      }
    }
    return null;
  }

  public static Element findChild(Element parent, String name) {
    Element res = getChild(parent, name);
    ItCheck.input(res != null);
    return res;
  }

  public static List<Element> getChildren(Element parent, String name) {
    List<Element> res = new ArrayList<>();

    for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
      Element e = toElementIfNameMatches(n, name);
      if (e != null) {
        res.add(e);
      }
    }

    return res;
  }

  private XmlUtils() {}
}
